package com.spsy.pay.controller;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OrderBatchInsert {
    // 数据库连接信息（替换为你的实际配置）
    private static final String URL = "jdbc:mysql://localhost:3306/ry_2303a_cloud?useSSL=false&rewriteBatchedStatements=true";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) throws Exception {
        int total = 100000; // 总记录数
        int batchSize = 1000; // 每批次插入数量
        int threadNum = 5; // 线程数

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        CountDownLatch latch = new CountDownLatch(threadNum);

        long startTime = System.currentTimeMillis();

        // 分配任务给线程
        for (int t = 0; t < threadNum; t++) {
            final int threadId = t;
            executor.submit(() -> {
                try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
                    conn.setAutoCommit(false); // 关闭自动提交，提升性能
                    PreparedStatement ps = conn.prepareStatement(
                        "INSERT INTO `order` (order_no, user_id, total_amount, create_time) " +
                        "VALUES (?, ?, ?, NOW())"
                    );

                    // 计算当前线程需要处理的记录范围
                    int start = threadId * (total / threadNum);
                    int end = (threadId == threadNum - 1) ? total : (threadId + 1) * (total / threadNum);

                    for (int i = start; i < end; i++) {
                        // 设置参数（模拟订单数据）
                        ps.setString(1, "ORD" + System.currentTimeMillis() + i); // 订单号
                        ps.setLong(2, 10000 + (i % 1000)); // 用户ID（模拟1000个用户）
                        ps.setBigDecimal(3, new java.math.BigDecimal(Math.random() * 1000 + 100)); // 订单金额

                        ps.addBatch(); // 加入批处理

                        // 达到批次大小就执行一次
                        if ((i + 1) % batchSize == 0) {
                            ps.executeBatch();
                            conn.commit();
                            ps.clearBatch();
                        }
                    }

                    // 处理剩余数据
                    ps.executeBatch();
                    conn.commit();
                    System.out.println("线程" + threadId + "完成，插入" + (end - start) + "条");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown(); // 线程完成，计数器减1
                }
            });
        }

        latch.await(); // 等待所有线程完成
        executor.shutdown();

        long endTime = System.currentTimeMillis();
        System.out.println("全部完成！总耗时：" + (endTime - startTime) + "ms");
    }
}